package com.example.translateappjava.Activity;

import static com.example.translateappjava.Activity.MainActivity.increaseCursorWindowSize;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.translateappjava.DataBase.UserDbHelper;
import com.example.translateappjava.R;
import com.example.translateappjava.DataBase.UserInfo;
import com.example.translateappjava.Singleton.GlobalData;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {

    private EditText et_username;
    private EditText et_password;
    private SharedPreferences mSharedPreferences;
    private CheckBox checkBox;
    private TextView forgotPassword;

    // 重置密码弹窗相关
    private Dialog resetPasswordDialog;
    private EditText et_reset_email;
    private EditText et_new_password;
    private EditText et_confirm_password;
    private EditText et_verification_code;
    private Button btn_get_code;
    private Button btn_confirm_reset;
    private Button btn_cancel;
    private CountDownTimer countDownTimer;

    private boolean is_login;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        increaseCursorWindowSize();

        mSharedPreferences = getSharedPreferences("user", MODE_PRIVATE);

        boolean isLogin = mSharedPreferences.getBoolean("is_login", false);
        String username = mSharedPreferences.getString("username", null);
        String password = mSharedPreferences.getString("password", null);

        et_username = findViewById(R.id.et_username);
        et_password = findViewById(R.id.et_password);
        checkBox = findViewById(R.id.checkbox);
        forgotPassword = findViewById(R.id.forgot_password);

        et_username.setText(username);
        et_password.setText(password);

        if (!et_username.getText().toString().isEmpty() && !et_password.getText().toString().isEmpty()) {
            if (isLogin) {
                // 如果用户已经登录，直接跳转到主界面
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                UserInfo login = UserDbHelper.getInstance(LoginActivity.this).login(username);
                UserInfo.setsUserInfo(login);
                startActivity(intent);
                finish();
                return; // 防止执行后续的初始化代码
            }
        }

        // 点击注册
        findViewById(R.id.to_register).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到注册
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });

        // 点击忘记密码
        forgotPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showResetPasswordDialog();
            }
        });

        // 登录按钮点击事件
        findViewById(R.id.login).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = et_username.getText().toString();
                String password = et_password.getText().toString();

                if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
                    Toast.makeText(LoginActivity.this, "请输入用户名和密码", Toast.LENGTH_SHORT).show();
                } else {
                    // 构造 JSON 请求体
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("userName", username);
                        jsonObject.put("password", password);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(LoginActivity.this, "构造请求失败", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    OkHttpClient client = new OkHttpClient();
                    RequestBody body = RequestBody.create(
                            jsonObject.toString(),
                            MediaType.parse("application/json; charset=utf-8")
                    );

                    // 模拟器使用 10.0.2.2 访问宿主机
                    Request request = new Request.Builder()
                            .url(GlobalData.getInstance().getBaseUrl() + "/user/login")
                            .post(body)
                            .build();

                    client.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            runOnUiThread(() -> Toast.makeText(LoginActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show());
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            if (!response.isSuccessful()) {
                                runOnUiThread(() -> Toast.makeText(LoginActivity.this, "服务器错误", Toast.LENGTH_SHORT).show());
                                return;
                            }

                            String responseStr = response.body().string();
                            try {
                                JSONObject result = new JSONObject(responseStr);
                                int code = result.getInt("code");
                                String msg = result.getString("msg");

                                runOnUiThread(() -> {
                                    if (code == 200) {
                                        Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();

                                        try {
                                            // 解析后端返回的用户信息
                                            JSONObject data = result.getJSONObject("data");
                                            JSONObject userInfo = data.getJSONObject("userInfo");
                                            JSONObject tokens = data.getJSONObject("tokens");

                                            // 提取用户信息
                                            String serverUsername = userInfo.getString("userName");
                                            String trueName = userInfo.optString("trueName", "");
                                            String gender = userInfo.optString("gender", "");
                                            String birthDay = userInfo.optString("birthDay", "");
                                            String email = userInfo.optString("email", "");
                                            String createdAt = userInfo.optString("createdAt", "");
                                            if (createdAt.length() >= 10) createdAt = createdAt.substring(0, 10);
                                            String height = userInfo.optString("height", "");
                                            String weight = userInfo.optString("weight", "");
                                            String phoneNumber = userInfo.optString("phoneNumber", "");
                                            String sportLevel = userInfo.optString("sportLevel", "");

                                            // 获取token信息（如果需要保存的话）
                                            String accessToken = tokens.optString("accessToken", "");
                                            String refreshToken = tokens.optString("refreshToken", "");

                                            UserDbHelper dbHelper = UserDbHelper.getInstance(LoginActivity.this);

                                            // 检查本地数据库是否已存在该用户
                                            boolean userExists = dbHelper.checkUsernameExists(serverUsername);

                                            if (!userExists) {
                                                // 用户不存在，先注册
                                                int registerResult = dbHelper.register(
                                                        serverUsername,     // username
                                                        password,           // password (使用用户输入的密码)
                                                        "",                 // nickname (填空)
                                                        gender,             // sex
                                                        birthDay,           // birth
                                                        trueName,           // name
                                                        createdAt           // registerDate
                                                );

                                                if (registerResult <= 0) {
                                                    Toast.makeText(LoginActivity.this, "本地用户信息保存失败", Toast.LENGTH_SHORT).show();
                                                    return;
                                                }
                                            }

                                            // 获取或创建用户信息对象并更新
                                            UserInfo localUserInfo = dbHelper.login(serverUsername);
                                            if (localUserInfo != null) {
                                                // 更新用户信息
                                                localUserInfo.setName(trueName);
                                                localUserInfo.setSex(gender);
                                                localUserInfo.setBirth(birthDay);
                                                localUserInfo.setEmail(email);
                                                localUserInfo.setHeight(height.equals("null") ? "" : height);
                                                localUserInfo.setWeight(weight.equals("null") ? "" : weight);
                                                localUserInfo.setPhoneNumber(phoneNumber.equals("null") ? "" : phoneNumber);
                                                localUserInfo.setSportLevel(sportLevel.equals("null") ? "" : sportLevel);

                                                // 更新到数据库
                                                int updateResult = dbHelper.updateUserInfo(localUserInfo);

                                                if (updateResult > 0) {
                                                    // 保存登录状态
                                                    SharedPreferences.Editor editor = mSharedPreferences.edit();
                                                    if (checkBox.isChecked()) {
                                                        editor.putString("username", username);
                                                        editor.putString("password", password);
                                                        editor.apply();
                                                    } else {
                                                        editor.clear();
                                                    }

                                                    // 可以选择保存token到SharedPreferences
                                                    editor.putString("accessToken", accessToken);
                                                    editor.putString("refreshToken", refreshToken);
                                                    editor.apply();

                                                    UserInfo.setsUserInfo(localUserInfo);

                                                    // 跳转主页面
                                                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                                    startActivity(intent);
                                                    finish();
                                                } else {
                                                    Toast.makeText(LoginActivity.this, "用户信息更新失败", Toast.LENGTH_SHORT).show();
                                                }
                                            } else {
                                                Toast.makeText(LoginActivity.this, "本地用户信息获取失败", Toast.LENGTH_SHORT).show();
                                            }

                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                            Toast.makeText(LoginActivity.this, "解析用户信息失败", Toast.LENGTH_SHORT).show();
                                        }

                                    } else if (code == 10002) {
                                        Toast.makeText(LoginActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                                    } else if (code == 10001) {
                                        Toast.makeText(LoginActivity.this, "该账号暂未注册", Toast.LENGTH_SHORT).show();
                                    } else {
                                        Toast.makeText(LoginActivity.this, "未知错误: " + msg, Toast.LENGTH_SHORT).show();
                                    }
                                });
                            } catch (JSONException e) {
                                runOnUiThread(() -> Toast.makeText(LoginActivity.this, "解析服务器响应失败", Toast.LENGTH_SHORT).show());
                            }
                        }
                    });
                }
            }
        });

        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // 直接更新SharedPreferences的is_login值
                SharedPreferences.Editor editor = mSharedPreferences.edit();
                editor.putBoolean("is_login", isChecked);
                editor.apply();
            }
        });
    }

    /**
     * 显示重置密码弹窗
     */
    private void showResetPasswordDialog() {
        resetPasswordDialog = new Dialog(this);
        resetPasswordDialog.setContentView(R.layout.dialog_reset_password);

        // 设置弹窗宽度
        Window window = resetPasswordDialog.getWindow();
        if (window != null) {
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = (int) (getResources().getDisplayMetrics().widthPixels * 0.9);
            window.setAttributes(params);
        }

        // 初始化弹窗控件
        et_reset_email = resetPasswordDialog.findViewById(R.id.et_reset_email);
        et_new_password = resetPasswordDialog.findViewById(R.id.et_new_password);
        et_confirm_password = resetPasswordDialog.findViewById(R.id.et_confirm_password);
        et_verification_code = resetPasswordDialog.findViewById(R.id.et_verification_code);
        btn_get_code = resetPasswordDialog.findViewById(R.id.btn_get_code);
        btn_confirm_reset = resetPasswordDialog.findViewById(R.id.btn_confirm_reset);
        btn_cancel = resetPasswordDialog.findViewById(R.id.btn_cancel);

        // 获取验证码按钮点击事件
        btn_get_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email = et_reset_email.getText().toString().trim();
                if (TextUtils.isEmpty(email)) {
                    Toast.makeText(LoginActivity.this, "请输入邮箱地址", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
                    Toast.makeText(LoginActivity.this, "请输入有效的邮箱地址", Toast.LENGTH_SHORT).show();
                    return;
                }

                sendVerificationCode(email);
            }
        });

        // 确认重置按钮点击事件
        btn_confirm_reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resetPassword();
            }
        });

        // 取消按钮点击事件
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (countDownTimer != null) {
                    countDownTimer.cancel();
                }
                resetPasswordDialog.dismiss();
            }
        });

        resetPasswordDialog.show();
    }

    /**
     * 发送验证码
     */
    private void sendVerificationCode(String email) {
        OkHttpClient client = new OkHttpClient();

        // 根据新的API要求，email参数应该在params里，使用URL参数方式
        HttpUrl.Builder urlBuilder = HttpUrl.parse(GlobalData.getInstance().getBaseUrl() + "/user/getResetPswToken").newBuilder();
        urlBuilder.addQueryParameter("email", email);
        String url = urlBuilder.build().toString();

        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create("", MediaType.parse("application/json; charset=utf-8"))) // POST请求需要body，即使是空的
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> Toast.makeText(LoginActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    runOnUiThread(() -> Toast.makeText(LoginActivity.this, "服务器错误", Toast.LENGTH_SHORT).show());
                    return;
                }

                String responseStr = response.body().string();
                try {
                    JSONObject result = new JSONObject(responseStr);
                    int code = result.getInt("code");
                    String msg = result.getString("msg");

                    runOnUiThread(() -> {
                        if (code == 200) {
                            Toast.makeText(LoginActivity.this, "验证码已发送到您的邮箱", Toast.LENGTH_SHORT).show();
                            startCountDown();
                        } else if (msg.equals("该邮箱未绑定")) {
                            Toast.makeText(LoginActivity.this, "该邮箱未绑定", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (JSONException e) {
                    runOnUiThread(() -> Toast.makeText(LoginActivity.this, "解析服务器响应失败", Toast.LENGTH_SHORT).show());
                }
            }
        });
    }

    /**
     * 开始倒计时
     */
    private void startCountDown() {
        btn_get_code.setEnabled(false);
        countDownTimer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                btn_get_code.setText("重新获取(" + millisUntilFinished / 1000 + ")");
            }

            @Override
            public void onFinish() {
                btn_get_code.setEnabled(true);
                btn_get_code.setText("获取验证码");
            }
        };
        countDownTimer.start();
    }

    /**
     * 重置密码
     */
    private void resetPassword() {
        String email = et_reset_email.getText().toString().trim();
        String newPassword = et_new_password.getText().toString().trim();
        String confirmPassword = et_confirm_password.getText().toString().trim();
        String verificationCode = et_verification_code.getText().toString().trim();

        // 输入验证
        if (TextUtils.isEmpty(email)) {
            Toast.makeText(this, "请输入邮箱地址", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(newPassword)) {
            Toast.makeText(this, "请输入新密码", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(confirmPassword)) {
            Toast.makeText(this, "请再次输入新密码", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!newPassword.equals(confirmPassword)) {
            Toast.makeText(this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(verificationCode)) {
            Toast.makeText(this, "请输入验证码", Toast.LENGTH_SHORT).show();
            return;
        }

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("email", email);
            jsonObject.put("password", newPassword);
            jsonObject.put("reSetT", verificationCode); // 修改为 reSetT
        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(this, "构造请求失败", Toast.LENGTH_SHORT).show();
            return;
        }

        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(
                jsonObject.toString(),
                MediaType.parse("application/json; charset=utf-8")
        );

        Request request = new Request.Builder()
                .url(GlobalData.getInstance().getBaseUrl() + "/user/resetPsw")
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> Toast.makeText(LoginActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    runOnUiThread(() -> Toast.makeText(LoginActivity.this, "服务器错误", Toast.LENGTH_SHORT).show());
                    return;
                }

                String responseStr = response.body().string();
                try {
                    JSONObject result = new JSONObject(responseStr);
                    int code = result.getInt("code");
                    String msg = result.getString("msg");

                    runOnUiThread(() -> {
                        if (code == 200) {
                            Toast.makeText(LoginActivity.this, "密码重置成功，请使用新密码登录", Toast.LENGTH_LONG).show();
                            if (countDownTimer != null) {
                                countDownTimer.cancel();
                            }
                            resetPasswordDialog.dismiss();
                        } else if (msg.equals("验证码错误")) {
                            Toast.makeText(LoginActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (JSONException e) {
                    runOnUiThread(() -> Toast.makeText(LoginActivity.this, "解析服务器响应失败", Toast.LENGTH_SHORT).show());
                }
            }
        });
    }

    public void clearLoginPreferences() {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.remove("is_login");
        editor.remove("username");
        editor.remove("password");
        editor.apply();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }
}